package services

import (
	"awesome-devops/applications/models"
	"awesome-devops/applications/scheduler"
	"awesome-devops/applications/tools"
	"reflect"
	"strconv"
)

type WebHookService struct {
}

func (webHookService *WebHookService) CreateAutoDeploy(accessToken string, commitId string, commitMessage string) {
	project, err := models.GetProjectByAccessToken(accessToken)
	if err != nil {
		tools.GetLogger().Debug("无效项目:" + accessToken)
		return
	}
	locker, err := tools.GetProjectLocker(project)
	if err != nil {
		tools.GetLogger().Error("获取任务锁失败:项目名称" + project.ProjectName + "项目ID:" + strconv.Itoa(int(project.ID)))
		return
	}
	defer locker.Unlock()
	deployService := DeployService{}
	command, err := models.GetGitCommand(*project)
	if err != nil {
		return
	}
	_, err = command.PullAll(project.Branch)
	if err != nil {
		return
	}
	result := deployService.CreateDeploy(int(project.ID), commitId, "webhook自动触发:"+commitMessage)
	if reflect.TypeOf(result).Kind() == reflect.Int {
		//成功
		scheduler.GetScheduler().Run(result.(int))
	}

}
